<?
namespace Api\Model
{
	/** DB
	 * @desc: Allow to access to database by PDO
	**/
	abstract class	DB extends \Api\Model
	{		
						
		public function __initModel($config)
		{
			if(! array_key_exists('Database', $config)) 
				throw new \Exception("DB: DATABASE CONFIG DOESN'T EXISTS!");

			$dbconf = $config['Database'];		

			if(!(array_key_exists('method',$dbconf) && array_key_exists('name',$dbconf) &&
			array_key_exists('pass',$dbconf) && array_key_exists('user',$dbconf)))
				throw new \Exception("DB: INVALID CONFIG, MISING ONE OR MORE FIELD");
									
			$this->m_handle = new \PDO($dbconf['method'].':host='.$dbconf['host'].';dbname='.$dbconf['name'],$dbconf['user'],$dbconf['pass'], array_key_exists('addition',$dbconf)?$dbconf['addition']:array());	
				
				
			return $config;
		}			

			
		/** Prepare
		 * @desc: Warper for PDO::PREPARE. Autoassign parameters
		**/
		public function Prepare($query, array $params=array())
		{
			$_Q = $this->m_handle->prepare($query);
			foreach($params as $k => $v)
				$_Q->bindValue($k, $v[0], $v[1]);
							
			return $_Q;
		}
		
		/** Query
		 * @desc: Doing query
		**/
		public function Query($query, array $params=array())
		{
			$_Q = $this->Prepare($query, $params);			
			if($_Q->execute())			
				return( $_Q->fetchAll() );			
			return null;
		}
	}
}
?>